import axios from 'axios';
import Intcp from './http.intcp';
import qs from 'qs';
import aesUtils from './aes.utils'
import {Base64} from 'js-base64'
import md5 from 'js-md5';

Intcp.interceptors();

function axiosPost(url, params) {
  const promise = new Promise((resolve, reject) => {
    axios.post(url, qs.stringify(params)).then((response) => {
      resolve(response.data);
    }).catch((err) => {
      console.log(reject(err));
      reject(err);
    });
  });
  return promise;
}

function axiosPostRequest(url, params, config) {
  const promise = new Promise((resolve, reject) => {
    axios.post(url, params, config).then((response) => {
      resolve(response.data);
    }).catch((err) => {
      reject(err);
    });
  });
  return promise;
}

function axiosGet(url, params) {
  const promise = new Promise((resolve, reject) => {
    axios.get(url, {params}).then((response) => {
      response.data = response.data || {};
      resolve(response.data);
    }).catch((err) => {
      console.log(reject(err));
      reject(err);
    });
  });
  return promise;
}

function axiosGetEncrypt(url, params) {
  const promise = new Promise((resolve, reject) => {
    axios.get(url, {params}).then((response) => {
      response.data = response.data || {};
      if (PUZZLE_CONFIG.apiSecurity) {
        let data = Base64.decode(response.data.data);
        response.data.data = JSON.parse(data)
      }
      resolve(response.data);
    }).catch((err) => {
      console.log(reject(err));
      reject(err);
    });
  });
  return promise;
}


function axiosGetRequest(url, params) {
  const promise = new Promise((resolve, reject) => {
    axios.get(url + "?" + qs.stringify(params), {}).then((response) => {
      response.data = response.data || {};
      resolve(response.data);
    }).catch((err) => {
      console.log(reject(err));
      reject(err);
    });
  });
  return promise;
}

function axiosDelete(url, params) {
  const promise = new Promise((resolve, reject) => {
    axios.delete(url, params).then((response) => {
      resolve(response.data);
    }).catch((err) => {
      reject(err);
    });
  });
  return promise;
}

function axiosPut(url, params) {
  const promise = new Promise((resolve, reject) => {
    axios.put(url, params).then((response) => {
      resolve(response.data);
    }).catch((err) => {
      console.log(reject(err));
      reject(err);
    });
  });
  return promise;
}

function axiosPutRequest(url, params, config) {
  const promise = new Promise((resolve, reject) => {
    axios.put(url, params, config).then((response) => {
      resolve(response.data);
    }).catch((err) => {
      // console.log(reject(err));
      reject(err);
    });
  });
  return promise;
}

function axiosPatch(url, params) {
  const promise = new Promise((resolve, reject) => {
    axios.patch(url, params).then((response) => {
      resolve(response.data);
    }).catch((err) => {
      console.log(reject(err));
      reject(err);
    });
  });
  return promise;
}


function axiosGetAll(url, params, config) {
  const promise = new Promise((resolve, reject) => {
    axios.get(url, params, config).then((response) => {
      resolve(response);
    }).catch((err) => {
      reject(err);
    });
  });
  return promise;
}
/**
 *
 * @param URL 下载地址
 * @param mode 下载方式 get post
 * @param name 下载文件名
 * @param param 参数
 * @param fileType 下载文件格式
 * @author wangwuhui
 * @date 2020-08-06
 */
function downloadUrlMode(url, mode, name, param, fileType) {
  const promise = new Promise((resolve, reject) => {
    axios({
      url: url,
      method: mode,
      data: param,
      headers: {
        Authentication: sessionStorage.getItem('token'),
        Accept: 'application/json'
      },
      responseType: 'arraybuffer'
    }).then(response => {
      const blob = new Blob([response.data], {type: 'application/' + fileType})
      resolve(response.data);
      let fileName;
      // debugger
      if (name) {
        fileName = name + "." + fileType
      } else {
        //下载文件名
        let fileNames = response.headers['content-disposition'];
        if (fileNames) {
          fileName = window.decodeURI(fileNames.split('=')[1], "UTF-8");
        }
      }
      let link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      window.setTimeout(function () {
        URL.revokeObjectURL(blob)
        document.body.removeChild(link)
      }, 0)

    })
  });
  return promise;

  /*axios({
    url: url,
    method: mode,
    data: param,
    headers: {
      Authentication: sessionStorage.getItem('token'),
      Accept: 'application/json'
    },
    responseType: 'arraybuffer'
  }).then(response => {
    const blob = new Blob([response.data], {type: 'application/' + fileType})
    const fileName = name + "." + fileType
    let link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    window.setTimeout(function () {
      URL.revokeObjectURL(blob)
      document.body.removeChild(link)
    }, 0)
*/
  }


function downloadUrl(URL, name) {
  console.log(URL, name);
  axios({
    method: 'get',
    url: URL,
    headers: {
      Authentication: sessionStorage.getItem('token'),
      Accept: 'application/json'
    },
    responseType: 'blob'
  }).then(response => {
    let blob = new Blob([response.data], {type: 'application/zip'})
    let downloadElement = document.createElement('a')
    let url = window.URL.createObjectURL(blob)
    downloadElement.href = url
    downloadElement.download = name + ".zip"
    downloadElement.click()
    window.URL.revokeObjectURL(url)
  })
}


function viewUrl(URL,type) {
  let url 
  const promise = new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url: URL,
      headers: {
        Authentication: sessionStorage.getItem('token'),
        Accept: 'application/json'
      },
      responseType: 'blob'
    }).then((response) => {
      // { type: "image/png" } "text/xml"
      // let blob = new Blob([response.data], { type: type || 'image/png' });
      let blob = new Blob([response.data], {type:'image/png'});
      url = window.URL.createObjectURL(blob);  
      resolve(url);
    }).catch((err) => {
      console.log(reject(err));
      reject(err);
    });
  })
  return promise 

}


function uploadFile(URL, formData) {
  let url = URL
  let headers = {'Content-Type': 'multipart/form-data'}
  return axios.post(url, formData, {headers: headers})
}

function downloadMB(URL) {
  console.log(URL);
  axios({
    method: 'get',
    url: URL,
    headers: {
      Authentication: sessionStorage.getItem('token'),
      Accept: 'application/json'
    },
    responseType: 'blob'
  }).then(response => {
    let blob = new Blob([response.data], {type: 'application/txt'})
    let downloadElement = document.createElement('a')
    let url = window.URL.createObjectURL(blob)
    downloadElement.href = url
    downloadElement.download = '硬件模板' + ".txt"
    downloadElement.click()
    window.URL.revokeObjectURL(url)
  })
}

function axiosPostEncrypt(url, params) {
  const promise = new Promise((resolve, reject) => {
    if (PUZZLE_CONFIG.apiSecurity) {
      params.tmp_flg = new Date().getTime();
      params.nonce_flg = params.nonce_flg = md5(new Date().getTime() +""+ Math.ceil(Math.random() * 9000 + 1000));
      params = aesUtils.encode(JSON.stringify(params));
    }
    axios.post(url, params, {
      headers: {
        'content-type': 'application/json',
      }
    }).then((response) => {
      resolve(response.data);
    }).catch((err) => {
      console.log(reject(err));
      reject(err);
    });
  });
  return promise;
}

function axiosPutEncrypt(url, params) {
  const promise = new Promise((resolve, reject) => {
    if (PUZZLE_CONFIG.apiSecurity) {
      params.tmp_flg = new Date().getTime();
      params.nonce_flg = md5(new Date().getTime() +""+  Math.ceil(Math.random() * 9000 + 1000));
      params = aesUtils.encode(JSON.stringify(params));
    }
    axios.put(url, params, {
      headers: {
        'content-type': 'application/json',
      }
    }).then((response) => {
      resolve(response.data);
    }).catch((err) => {
      console.log(reject(err));
      reject(err);
    });
  });
  return promise;
}

export default {

  post: axiosPost,
  postEncrypt: axiosPostEncrypt,
  get: axiosGet,
  getEncrypt: axiosGetEncrypt,
  delete: axiosDelete,
  put: axiosPut,
  putEncrypt: axiosPutEncrypt,
  patch: axiosPatch,
  downloadUrl: downloadUrl,
  downloadMB: downloadMB,
  viewUrl: viewUrl,
  downloadUrlMode: downloadUrlMode,

  postRequest: axiosPostRequest,
  putRequest: axiosPutRequest,
  getRequest: axiosGetRequest,
  uploadFile: uploadFile,
  getAll: axiosGetAll
};
